package dao

import (
	"context"
	"fmt"
	"time"

	"github.com/nsqio/go-nsq"
	"github.com/patrickmn/go-cache"
	"gorm.io/gorm"

	"wxpay/internal/model"
)

type AlipayAgent interface {
	// 获取配置信息
	GetAgentByAppId(ctx context.Context, appId string) (*model.AlipayAgent, error)
	// 获取配置信息 from cache
	GetAgentFromCache(ctx context.Context, appId string) (*model.AlipayAgent, error)
}

type aAgentRepo struct {
	*gorm.DB
	producer *nsq.Producer
	cache    *cache.Cache
}

func NewAlipayAgentRepo(d *gorm.DB, p *nsq.Producer, c *cache.Cache) *aAgentRepo {
	return &aAgentRepo{
		DB:       d,
		producer: p,
		cache:    c,
	}
}

// 根据 APP id 获取配置信息
func (a *aAgentRepo) GetAgentByAppId(_ context.Context, appId string) (*model.AlipayAgent, error) {
	resp := &model.AlipayAgent{}
	err := a.DB.Model(resp).Where("app_id = ?", appId).First(&resp).Error
	return resp, err
}

// 从缓存获取配置信息
func (a *aAgentRepo) GetAgentFromCache(ctx context.Context, appId string) (*model.AlipayAgent, error) {
	cacheKey := fmt.Sprintf("alipay-agent-%s", appId)
	if config, found := a.cache.Get(cacheKey); found {
		agent, ok := config.(*model.AlipayAgent)
		if ok {
			return agent, nil
		}
	}
	agent, err := a.GetAgentByAppId(ctx, appId)
	if err != nil {
		return nil, err
	}
	a.cache.Set(cacheKey, agent, 10*time.Hour)
	return agent, nil
}
